<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\common\Common;
use app\common\UserService;
use app\job\Task;
use app\model\Config;
use app\model\PointGoods;
use app\model\PointGoodsAssess;
use app\model\PointGoodsClass;
use app\model\PointGoodsOrders;
use app\model\PointGoodsOrdersDetail;
use app\model\PointGoodsSpec;
use app\model\User;
use app\tool\Random;
use GuzzleHttp\Client;
use think\db\Query;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\facade\Queue;

class PointGoodsController extends BaseController
{
	protected $order_timeout = 60*15;//订单超时时间
	
	
	/**
	 * 类目
	 * @return void
	 */
	function class()
	{
		$rows = PointGoodsClass::where(['pid' => 0])->order(['id' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	/**
	 * 类目
	 * @return void
	 */
	function classDetail()
	{
		$id = $this->request->get('id/d');
		if (empty($id)) {
			$this->writeJson(0, '参数错误');
		}
		$rows = PointGoodsClass::where(['pid' => $id])->order(['id' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	function list()
	{
		$first_class_id = $this->request->get('first_class_id/d'); #必填
		$second_class_id = $this->request->get('second_class_id/d');
		$price = $this->request->get('price');
		$sales = $this->request->get('sales');
		$keyword = $this->request->get('keyword');
		$rows = PointGoods::withMin(['spec' => 'min_price'], 'price')
			->when(!empty($second_class_id), function (Query $query) use ($second_class_id) {
				$query->where(['class_id' => $second_class_id]);
			}, function (Query $query) use ($first_class_id) {
				$second_class_ids = PointGoodsClass::where(['pid' => $first_class_id])->column('id');
				$query->whereIn('class_id', $second_class_ids)->order(['weigh' => 'desc']);
			})->when(!empty($price), function (Query $query) use ($price) {
				$query->order(['min_price' => $price]);
			})->when(!empty($sales), function (Query $query) use ($sales) {
				$query->order(['sales' => $sales]);
			})
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('name', '%' . $keyword . '%');
			})
			->order(['id'=>'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	function detail()
	{
		$goods_id = $this->request->get('goods_id/d');
		$address = Config::getFieldByName('address','value');
		$row = PointGoods::withMin(['spec' => 'min_price'], 'price')->with(['spec'])->filter(function ($data)use($address) {
			$data->address = $address;
			$res = Common::getWechatQrcode('pages/index/integralGoodsDetail',$data->id);
			$data->qrdata = 'data:image/png;base64,' . base64_encode($res);
		})->findOrFail($goods_id);
		$this->writeJson($row);
	}
	
	function assessList()
	{
		$goods_id = $this->request->get('goods_id/d');
		$type = $this->request->get('type/d');
		$rows = PointGoodsAssess::where(['goods_id' => $goods_id])
			->with(['user', 'spec'])
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->where('score', 5);
				}
				if ($type == 2) {
					$query->whereBetween('score', [2, 4]);
				}
				if ($type == 3) {
					$query->where('score', 1);
				}
				if ($type == 4) {
					$query->where('images', '<>', '');
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		foreach ($rows as $row){
			if ($row->anonymous == 1){
				$row->user->nickname = '匿名';
			}
		}
		$assess_count = PointGoodsAssess::where(['goods_id' => $goods_id])->count();//总数
		$good_count = PointGoodsAssess::where(['goods_id' => $goods_id])->where('score', 5)->count();//好评
		$just_count = PointGoodsAssess::where(['goods_id' => $goods_id])->whereBetween('score', [2, 4])->count();//中评
		$bad_count = PointGoodsAssess::where(['goods_id' => $goods_id])->where('score', 1)->count();//差评
		$images_count = PointGoodsAssess::where(['goods_id' => $goods_id])->where('images', '<>', '')->count();//有图
		$this->writeJson(['count' => $assess_count, 'good_count' => $good_count, 'just_count' => $just_count, 'bad_count' => $bad_count, 'images_count' => $images_count, 'list' => $rows]);
	}
	
	/**
	 * 价格计算
	 * @return void
	 */
	function getPrice()
	{
		$spec_id = $this->request->get('spec_id/d');
		$num = $this->request->get('num/d');
		$spec = PointGoodsSpec::with(['goods'])->findOrFail($spec_id);
		$address = \app\model\Config::getFieldByName('address','value');
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		$total_amount = bcmul((string)$num ,(string)$spec->price,2);//总金额=数量*规格单价
		$pay_amount = $total_amount;
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		$this->writeJson(['spec' => $spec,'address'=>$address, 'pay_amount' => $pay_amount, 'total_amount' => $total_amount]);
	}
	
	/**
	 * 创建订单
	 * @return void
	 */
	function createOrder()
	{
		$take_delivery_id = $this->request->post('take_delivery_id/d'); //提货人
		$spec_id = $this->request->post('spec_id/d'); //规格
		$num = $this->request->post('num/d', 1); //数量
		$mark = $this->request->post('mark', ''); //备注
		if (empty($take_delivery_id)){
			$this->writeJson(0, '提货人不能为空');
		}
		
		$spec = PointGoodsSpec::findOrFail($spec_id);
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		//修改库存
		$spec->sku -= 1;
		$spec->save();
		$total_amount = $num * $spec->price;//原价=数量*规格单价+运费
		
		$pay_amount = $total_amount;
		if ($pay_amount <= 0) {
			$pay_amount = 0.01;
		}
		
		$ordersn = Random::ordersn();
		$data = [
			'user_id' => $this->user_id,
			'take_delivery_id' => $take_delivery_id,
			'pay_amount' => $pay_amount, //原价-优惠券金额
			'order_sn' => $ordersn,
			'mark' => $mark,
		];
		// 启动事务
		Db::startTrans();
		try {
			UserService::changeUserScore(-$pay_amount, $this->user_id, '购买商品');
			$order = PointGoodsOrders::create($data);
			$order->detail()->save([
				'goods_id' => $spec->goods_id,
				'spec_id' => $spec_id,
				'amount' => $spec->price * $num ,
				'num' => $num,
			]);
			
			app(NotifyController::class)->returnNotify($this->request->setRoute(['paytype' => 'balance', 'out_trade_no' => $ordersn, 'attach' => 'point_goods']));
			
			// 提交事务
			Db::commit();
		} catch (\Exception|HttpResponseException $e) {
			// 回滚事务
			Db::rollback();
			if ($e instanceof HttpResponseException){
				$responseDate = $e->getResponse()->getData();
				$this->writeJson(0, $responseDate['msg']);
			}
			$this->writeJson(0, $e->getMessage());
		}
		
		Queue::later($this->order_timeout, Task::class, ['order_id' => $order->id, 'action' => 'point_goods_order_timeout'], 'task');
		$this->writeJson(['order_id' => $order->id]);
	}
	
	/**
	 * 订单列表
	 * @return void
	 */
	function orderList()
	{
		$status = $this->request->get('status/d'); // 0全部 1待取货 2完成 3取消
		$rows = PointGoodsOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			}])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['pay_status' => 2]);
						break;
					case 2:
						$query->whereIn('pay_status',[3,4]);
						break;
					case 3:
						$query->where(['pay_status'=>5]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#订单详情
	function orderDetail()
	{
		$order_id = $this->request->get('order_id/d');
		$address = \app\model\Config::getFieldByName('address','value');
		
		$row = PointGoodsOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			}, 'take_delivery'])
			->filter(function ($data)use($address){
				$data->address = $address;
				if ($data->pay_status == 1){
					$data->canceltime_s = strtotime($data->createtime) + $this->order_timeout;
					$data->createtime_s = $data->getData('createtime');
				}
			})
			->findOrFail($order_id);
		$this->writeJson($row);
	}
	
	#订单详情列表
	function orderDetailList()
	{
		$order_id = $this->request->get('order_id/d');
		$rows = PointGoodsOrders::where(['order_id' => $order_id])
			->with(['goods','spec'])
			->select();
		$this->writeJson($rows);
	}

	
	/**
	 * 订单删除
	 * @return void
	 */
	function orderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$row = PointGoodsOrders::where(['user_id' => $this->user_id,['pay_status','in', [4,5]]])->findOrFail($order_id);
		$row->delete();
		$this->writeJson();
	}
	

	
	/**
	 * 订单确认
	 * @return void
	 */
	function orderConfirm()
	{
		$order_id = $this->request->post('order_id/d');
		$row = PointGoodsOrders::where(['user_id' => $this->user_id])->findOrFail($order_id);
		if ($row->pay_status != 2) {
			$this->writeJson(0, '订单状态异常');
		}
		$row->pay_status = 3;
		$row->save();
		$this->writeJson();
	}
	
	/**
	 * 订单评价
	 * @return void
	 */
	function orderAssess()
	{
		$order_id = $this->request->post('order_id/d');
		$score = $this->request->post('score/d', 5);
		$images = $this->request->post('images', '');
		$content = $this->request->post('content', '');
		$anonymous = $this->request->post('anonymous/d', 1);
		if (!$content) {
			$this->writeJson(0, '评论内容不能为空');
		}
		$orderDetail = PointGoodsOrdersDetail::where(['order_id'=>$order_id])->findOrFail();
		
		PointGoodsAssess::create([
			'user_id' => $this->user_id,
			'goods_id' => $orderDetail->goods_id,
			'order_detail_id' => $orderDetail->id,
			'spec_id' => $orderDetail->spec_id,
			'score' => $score,
			'images' => $images,
			'content' => $content,
			'anonymous' => $anonymous,
		]);
		$orderDetail->assess = 1;
		$assess = $orderDetail->orders->detail()->where(['assess'=>2,['id','<>',$orderDetail->id]])->find();
		if (!$assess){
			$orderDetail->orders->pay_status = 4;
		}
		$orderDetail->together(['orders'])->save();
		$this->writeJson();
	}
	
	function adminOrderList()
	{
		$status = $this->request->get('status/d'); // 1待取货  2已完成
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		$rows = PointGoodsOrders::with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			},'take_delivery'])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['pay_status' => 2]);
						break;
					case 2:
						$query->whereIn('pay_status', [3, 4]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 订单确认
	 * @return void
	 */
	function adminOrderConfirm()
	{
		$order_id = $this->request->post('order_id/d');
		$row = PointGoodsOrders::findOrFail($order_id);
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		if ($row->pay_status != 2) {
			$this->writeJson(0, '订单状态异常');
		}
		$row->pay_status = 3;
		$row->save();
		$this->writeJson();
	}
	
	#订单删除
	function adminOrderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$user = User::find($this->user_id);
		if (!$user){
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type!=2){
			$this->writeJson(0, '你没有核销权限');
		}
		$row = PointGoodsOrders::where([['pay_status','in', [4,5]]])->findOrFail($order_id);
		$row->delete();
		$this->writeJson();
	}
	
}
